package com.mike.validators;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

import org.w3c.tidy.Tidy;
import org.w3c.tidy.TidyMessage;
import org.w3c.tidy.TidyMessage.Level;
import org.w3c.tidy.TidyMessageListener;

import com.mike.model.IsValidationResult;


public class TidyValidator implements IsHTMLValidator {
	
	public static class NullOutputStream extends OutputStream {
		@Override
		public void write(int b) throws IOException {
		}
	}

	public static class HTMLHasErrors implements TidyMessageListener, IsValidationResult {

		private final String	m_resourceName;
		private boolean m_hasErrors		= false;
		private boolean m_hasWarnings	= false;
		
		public HTMLHasErrors(String resourceName){
			m_resourceName = resourceName;
		}
		
		@Override
		public boolean hasError(){
			return m_hasErrors;
		}
		
		@Override
		public boolean hasWarning(){
			return m_hasWarnings;
		}
		
		@Override
		public String getResourceName(){
			return m_resourceName;
		}
		
		@Override
		public void messageReceived(TidyMessage message) {
			if(message.getLevel() == Level.ERROR)
				m_hasErrors = true;
			if(message.getLevel() == Level.WARNING)
				m_hasWarnings = true;
		}
		

		
	}
	
	private Tidy tidy = new Tidy();
	
	public TidyValidator(){
		tidy.setXHTML(false);	
	}
	
	
	@Override
	public IsValidationResult validateHTML(File file) throws Exception{
		HTMLHasErrors hasErrors = new HTMLHasErrors(file.getName());
		tidy.setMessageListener(hasErrors);
		try {
			tidy.parse(new FileInputStream(file), new NullOutputStream());
			throw new Exception("not fully implemented");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return hasErrors;
	}

	@Override
	public IsValidationResult validateHTML(URL url) throws Exception{
		throw new Exception("not implemented");
	}

}
